//
//  MVVMViewController.m
//  DebugDemo
//
//  Created by XFB on 2018/11/15.
//  Copyright © 2018年 ZhouCheng. All rights reserved.
//

#import "MVVMViewController.h"

#import "VMDataSource.h"
#import "MVPCell.h"
#import "ViewModel.h"
#import "Model.h"

#import "MVVMDemoViewController.h"

static NSString *const reuserId = @"MVPCell";

@interface MVVMViewController ()

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ViewModel *viewModel;
@property (nonatomic, strong) VMDataSource *dataSource;

@end

@implementation MVVMViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupBasicSet];
    [self setupUI];
}

- (void)setupBasicSet
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"MVVM编程";
    
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"MVVM" style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonItemDidClick:)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
}

- (void)rightBarButtonItemDidClick:(UIBarButtonItem *)button
{
    NSLog(@"MVVM2 Demo点击");
    MVVMDemoViewController *vc = [[MVVMDemoViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
//    self.tableView.transform = CGAffineTransformMakeRotation(- M_PI / 2);//旋转-90度
//    self.tableView.y = NavBarHeight;
}


- (void)setupUI
{
    __weak typeof(self) weakSelf = self;

    self.dataSource = [[VMDataSource alloc] initWithIdentifier:reuserId configureBlock:^(MVPCell *cell, Model *model, NSIndexPath * _Nonnull indexPath) {
        cell.nameLabel.text = model.name;
        cell.numberLabel.text = model.count;
        cell.count = [model.count intValue];
        cell.delegate = weakSelf.viewModel;
        cell.indexPath = indexPath;
    } selectBlock:^(NSIndexPath * _Nonnull indexPath) {
        NSLog(@"点击了%ld行", indexPath.row);
    } reloadDataBlock:^(NSMutableArray * _Nonnull array) {
        weakSelf.viewModel.dataArray = array;
    }];

    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self.dataSource;
    self.tableView.delegate = self.dataSource;
    
    self.viewModel = [[ViewModel alloc] init];
    [self.viewModel initWithBlock:^(id  _Nonnull data) {
        weakSelf.dataSource.dataArray = [weakSelf.viewModel.dataArray mutableCopy];
        [weakSelf.tableView reloadData];
    } failureBlock:^(id  _Nonnull data) {
        
    }];
    
    [self.viewModel loadData];
}


- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NavBarHeight, ScreenW, ScreenH-NavBarHeight-BottomHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView registerNib:[UINib nibWithNibName:@"MVPCell" bundle:nil] forCellReuseIdentifier:reuserId];
    }
    return _tableView;
}

@end
